var mongoose = require('mongoose');

var NotificationDB = {
	HOST: 'db.304lab.net',
	NAME: 'mongomq',
	QUEUE: 'queue',
};

var db = mongoose.createConnection(NotificationDB.HOST, NotificationDB.NAME);

db.on('error', console.error.bind(console, 'connection error.'));
db.on('open', function() {
	console.log('connected to ' + NotificationDB.NAME + ' database on ' + NotificationDB.HOST);
});

var Notification = db.model(NotificationDB.QUEUE, new mongoose.Schema({
	_id: String,
	data: {
		targets: String,
		cell: {
			username: String,
			content: String
		}
	},
	emitted: Date,
	event: String
}), NotificationDB.QUEUE);

exports.getNotifications = function(target, handler) {
	Notification.find({'data.targets': target}, 'event data.cell', {limit: 10, sort: {emitted: -1}}, function(error, rows) {
		handler(rows);
	});
};